package com.ruoyi.common.utils.file;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;

public class AliOss {

    private static String appId = "LTAI5tP9VRmczdpzMsxARpWM";
    private static String secret = "dwF2W3kqk8BOUsRC8V57nVmvJGYvsl";
    private static String endpoint = "oss-cn-shenzhen.aliyuncs.com";
    // 填写Bucket名称，例如examplebucket。
    private static String bucketName = "pay-oss-pay";

    public static void main(String[] args) throws Exception {
        String appId = "LTAI5tP9VRmczdpzMsxARpWM";
        String secret = "dwF2W3kqk8BOUsRC8V57nVmvJGYvsl";
        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String endpoint = "oss-cn-shenzhen.aliyuncs.com";
        // 从环境变量中获取访问凭证。运行本代码示例之前，请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // 填写Bucket名称，例如examplebucket。
        String bucketName = "pay-oss-pay";
        // 填写Object完整路径，完整路径中不能包含Bucket名称，例如exampledir/exampleobject.txt。
        String objectName = "yypay/1.jpg";
        // 填写本地文件的完整路径，例如D:\\localpath\\examplefile.txt。
        // 如果未指定本地路径，则默认从示例程序所属项目对应本地路径中上传文件。
        String filePath = "C:\\Users\\le\\Desktop\\1111\\5.jpg";

        // 创建OSSClient实例。
        //  OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);

        OSS ossClient = new OSSClientBuilder().build(endpoint, appId, secret);

        try {
            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, new File(filePath));
            // 如果需要上传时设置存储类型和访问权限，请参考以下示例代码。
            // ObjectMetadata metadata = new ObjectMetadata();
            // metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
            // metadata.setObjectAcl(CannedAccessControlList.Private);
            // putObjectRequest.setMetadata(metadata);

            // 上传文件。
            PutObjectResult result = ossClient.putObject(putObjectRequest);
            System.out.println(result.getResponse());
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    public static String upload(String objectName, File file) {
        // 填写Object完整路径，完整路径中不能包含Bucket名称，例如exampledir/exampleobject.txt。
//        String objectName = "yypay/1.jpg";
        OSS ossClient = new OSSClientBuilder().build(endpoint, appId, secret);

        try {
            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, file);
            // 上传文件。
            ossClient.putObject(putObjectRequest);
//https://pay-oss-pay.oss-cn-shenzhen.aliyuncs.com/yypay/1.jpg
            return "https://" + bucketName + "." + endpoint + "/" + objectName;

        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }


        return null;
    }

    public static String uploadToOss(MultipartFile uploadFile, String objectName) throws IOException {

        return uploadToOss(new ByteArrayInputStream(uploadFile.getBytes()),objectName);

    }

    public static String uploadToOss(byte buf[], String objectName)     {
        return uploadToOss(new ByteArrayInputStream(buf),objectName);
    }
    public static String uploadToOss(InputStream input, String objectName)     {
        OSS oss = new OSSClientBuilder().build(endpoint, appId, secret);
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName,input);
        // 上传文件。
        oss.putObject(putObjectRequest);
//https://pay-oss-pay.oss-cn-shenzhen.aliyuncs.com/yypay/1.jpg
        return "https://" + bucketName + "." + endpoint + "/" + objectName;

    }

}
